﻿using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Services;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;

namespace CoreShop.App
{
    public partial class frmCouponSel : UIForm
    {
        private corecmsuser member = null;
        public string sSelectTxt = "";
        public decimal allCouponAmount = 0;
        public List<VipCouponInfoModel> couponList = new List<VipCouponInfoModel>();
        public VipCouponInfoModel vipCouponInfo = null;
        private List<corecmsfoodordering> orderingDetail;
        public corecmsfoodorderingmaster orderingMaster;

        public frmCouponSel(corecmsuser _member, List<corecmsfoodordering> orderingDetail, corecmsfoodorderingmaster _orderingMaster)
        {
            InitializeComponent();
            this.member = _member;
            this.orderingDetail = orderingDetail;
            this.orderingMaster = _orderingMaster;
        }

        private async void frmfoodfeed_Load(object sender, System.EventArgs e)
        {
            string msg = "";
            lblMemberName.Text = "会员电话：" + member.mobile;            
            var orderCoupon = new OrderCouponPost();
            orderCoupon.storeId = AppConstVars.sysUser.storeId;
            orderCoupon.couponCode = "";
            orderCoupon.userId = member.id;
            orderCoupon.wxUserId = 0;
            orderCoupon.channel = 1;
            ShowWaitForm();
            try
            {
                couponList = await MemberApiUtil.GetCouponList(member.id.ToString(), AppConstVars.sysUser);
                BindCoupon();
            }
            finally { HideWaitForm(); }
            
        }

        private void BindCoupon()
        {
            if ((couponList != null) && (couponList.Count > 0))
            {
                int index = 1;
                string couponBatchId = "";
                foreach (var vipCoupon in couponList)
                {
                    if (!CheckCouponGoods(couponBatchId, vipCoupon)) continue;
                    DishItemInfo dish = new DishItemInfo();
                    dish.Name = vipCoupon.couponInfoId.ToString();
                    switch (CommFunc.ConvertToInt32(vipCoupon.couponTypeId))
                    {
                        case (int)GlobalEnumVars.CouponType.FullForCut:
                            dish.Money = "面值：￥" + vipCoupon.amount.ToString();
                            break;
                        case (int)GlobalEnumVars.CouponType.CouponDiscount:
                            dish.Money = string.Format("打{0}折", vipCoupon.amount.ToString());
                            break;
                        default:
                            dish.Money = "";
                            break;
                    }

                    dish.UnitName = "";
                    dish.LabelExist = $"{vipCoupon.couponBeginDate} - {vipCoupon.couponEndDate}";
                    var item = new UIDishItemCoupon(dish);
                    item.Tag = vipCoupon.couponInfoId.ToString();
                    item.TextName = vipCoupon.couponName;
                    item.Name = GetFoodItemName(index);
                    item.Margin = new System.Windows.Forms.Padding(3);
                    item.Click += Item_Click;
                    item.SetEnabled();
                    layList.Add(item);
                    couponBatchId = vipCoupon.couponBatchId;
                    index++;
                }
            }
        }

        private bool CheckCouponGoods(string couponBatchId, VipCouponInfoModel vipCoupon)
        {
            if (couponBatchId == vipCoupon.couponBatchId) return false;//相同的券，只加一个就可以
            //if (vipCoupon.verifyAmount > orderingMaster.sumAmount) return false; //使用门槛未达到
            if (vipCoupon.verifyAmount > orderingMaster.sumAllAmount) return false; //使用门槛未达到

            if (vipCoupon.itemWayType == (int)GlobalEnumVars.CouponItemWayType.AllGoods) return true;

            var stringList = vipCoupon.couponBatchSkuIdList;
            List<long> couponSkuId = new List<long>();
            foreach (string str in stringList)
            {
                couponSkuId.Add(CommFunc.ConvertToBigInt(str));
            }

            if (vipCoupon.itemWayType == (int)GlobalEnumVars.CouponItemWayType.IncludeGoods)
            {
                var couponGoods = orderingDetail.Where(p => couponSkuId.Contains(p.foodId)).ToList();
                if ((couponGoods == null) || (couponGoods.Count == 0)) return false;                  
            } 
            else
            if (vipCoupon.itemWayType == (int)GlobalEnumVars.CouponItemWayType.ExcludeGoods)
            {
                var couponGoods = orderingDetail.Where(p => !couponSkuId.Contains(p.foodId)).ToList();
                if ((couponGoods == null) || (couponGoods.Count == 0)) return false;
            }

            return true;
        }

        private void Item_Click(object sender, System.EventArgs e)
        {
            UIDishItemCoupon item = (UIDishItemCoupon)sender;
            vipCouponInfo = couponList.Find(p => p.couponInfoId == item.Tag.ToString());
            if (vipCouponInfo != null)
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        /// <summary>
        /// 商品按钮名称
        /// </summary>
        /// <param name="deskId"></param>
        /// <returns></returns>
        private string GetFoodItemName(int index)
        {
            return "uiFoodItem_" + index.ToString();
        }

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void frmCouponSel_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
        {
            HideWaitForm();
        }
    }
}
